package com.spring.mybatis.core;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;

/**
 * 获取 MapperScan 注解， 扫描 mapper 文件并注册 BeanDefinition
 * @author yangjian
 */
public class MybatisImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
	@Override
	public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry)
	{
		// 获取 MapperScan 注解
		Map<String, Object> attributes = metadata.getAnnotationAttributes(MapperScan.class.getName());
		String path = (String) attributes.get("value");
		// 扫描 mapper 路径
		MybatisClassPathBeanDefinitionScanner scanner = new MybatisClassPathBeanDefinitionScanner(registry);
		// spring 默认会过滤接口，并且需要添加 @Component 注解，这里添加一个过滤器，让所有的类默认都通过过滤器
		scanner.addIncludeFilter((metadataReader, metadataReaderFactory) -> true);
		// 开始扫描 BeanDefinition
		scanner.scan(path);
	}
}
